#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* func(void* args)
{
    char* str = static_cast<char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex); //申请访问
        pthread_cond_wait(&cond,&mutex); //访问环境变量 如果没有资源则挂起
        cout<<str<<"运行..."<<endl;
        pthread_mutex_unlock(&mutex); //释放锁
    }
    delete[] str;
    return nullptr;
}

int main()
{
    pthread_t arrt[5];
    for(int i = 0;i<5;++i)
    {
        char* str = new char[64];
        snprintf(str,64,"%s%d","thread-",i+1);
        pthread_create(arrt+i,nullptr,func,(void*)str);
    }

    sleep(3);

    while(true)
    {
        //pthread_cond_signal(&cond); //一个一个唤醒线程
        pthread_cond_broadcast(&cond); //一次唤醒所有等待线程
        cout<<"释放条件变量!"<<endl;
        sleep(1);
    }

    for(int i = 0;i<5;++i)
    {
        pthread_join(*(arrt+i),nullptr);
    }

    return 0;
}